package com.zzyl.nursing.service.impl;

import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-07
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() !=200){
            throw new BaseException("物联网接口 - 查询产品, 同步失败");
        }
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST,
                JSONUtil.toJsonStr(response.getProducts()),
                60 * 60 * 24 + (int) Math.random() * 100, TimeUnit.SECONDS);
    }

    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName,deviceDto.getDeviceName());
        if (count(queryWrapper) > 0){
            log.error("注册设备失败：设备名称 【{}】 重复",deviceDto.getDeviceName());
            throw new RuntimeException("注册设备失败:设备名称["+deviceDto.getDeviceName()+"] 重复");
        }
        queryWrapper.clear();
        queryWrapper.eq(Device::getNodeId,deviceDto.getNodeId());
        if (count(queryWrapper) >0){
            log.error("注册设备失败: 设备标识码 [{}] 重复",deviceDto.getNodeId());
            throw new RuntimeException("注册设备失败：设备名称 【" + deviceDto.getDeviceName() + "】 重复");
        }
        queryWrapper.clear();
        queryWrapper.eq(Device::getBindingLocation,deviceDto.getBindingLocation())
                .eq(Device::getLocationType,deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey,deviceDto.getProductKey());
        if (count(queryWrapper)>0){
            log.error("注册设备失败:同一位置绑定了相同产品的设备");
            throw new RuntimeException("注册设备失败:同一位置绑定了相同产品的设备");
        }
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.withNodeId(deviceDto.getNodeId())
                .withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey());
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-","");
        authInfo.withSecret(secret);
        addDevice.withAuthInfo(authInfo);
        addDeviceRequest.withBody(addDevice);
        AddDeviceResponse addDeviceResponse= null;
        try {
            addDeviceResponse = client.addDevice(addDeviceRequest);
        } catch (Exception e) {
            log.error("物联网平台-注册设备失败："+e.getMessage());
            throw new RuntimeException("注册设备失败"+e.getMessage());
        }
        if (addDeviceResponse.getHttpStatusCode() !=201){
            log.error("物联网平台-注册设备失败");
            throw new RuntimeException("注册设备失败：物联网平台-注册设备失败");
        }
        log.info("物联网平台-注册设备【{}】成功", deviceDto.getDeviceName());
        Device device = BeanUtil.toBean(deviceDto,Device.class);
        device.setIotId(addDeviceResponse.getDeviceId());
        device.setSecret(secret);
        if (device.getLocationType()==0){
            device.setPhysicalLocationType(-1);
        }
        try {
            save(device);
        } catch (Exception e) {
            log.error("注册设备失败："+e.getMessage());
            throw new RuntimeException("注册设备失败，原因："+e.getMessage());
        }
    }
}
